# -*- coding: utf-8 -*-
#
# @Author  : Yang
# @Email  : yangjiaxian@ibbd.net
# @Time    : 2022/11/16
import os

from src.common.logger import logger
from fastapi import APIRouter, Query, Path, Depends, File, UploadFile
from openpyxl import load_workbook

from settings import settings
from src.api.v1.fund.schemas import CreateFundParams, CreateFundResp, FetchFundsResp
from src.error import InternalException, status
from src.services.customer import CustomerServices
from src.services.fund import FundServices
from src.services.log import LogServices
from src.utils import output_json, check_operator

fund_app = APIRouter(tags=["基金"])


@fund_app.post("/funds", summary="新增客户基金数据", response_model=CreateFundResp)
async def create_fund_api(
        params: CreateFundParams,
        operator_id: int = Depends(check_operator)
):
    # 检查客户ID是否存在
    if not CustomerServices().fetch_one(params.customer_id):
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="客户ID不存在")

    # 新增客户基金数据
    fund_id = FundServices().create(**params.dict())

    LogServices().create(operator_id, f"新增了ID为{fund_id}，客户ID为{params.customer_id}的客户基金数据", params.dict())
    return output_json(data={"fund_id": fund_id}, message="")


@fund_app.delete("/funds/{fundId}", summary="删除客户基金数据", response_model=CreateFundResp)
async def delete_fund_api(
        fundId: int = Path(..., title="客户基金数据ID", description="客户基金数据ID"),
        operator_id: int = Depends(check_operator)
):
    result = FundServices().fetch_one(fundId)
    if not result:
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="客户基金数据ID已删除或不存在")

    FundServices().delete(fundId)
    LogServices().create(operator_id, f"删除了ID为{fundId}，客户ID为{result['customer_id']}的客户基金数据")
    return output_json(data={"fund_id": fundId}, message="")


@fund_app.put("/funds/{fundId}", summary="修改客户基金数据", response_model=CreateFundResp)
async def update_fund_api(
        params: CreateFundParams,
        fundId: int = Path(..., title="客户基金数据ID", description="客户基金数据ID"),
        operator_id: int = Depends(check_operator)
):
    result = FundServices().fetch_one(fundId)
    if not result:
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="客户基金数据ID已删除或不存在")

    FundServices().update(fundId, **params.dict())

    LogServices().create(operator_id, f"修改了ID为{fundId}的客户基金数据，客户ID为{params.customer_id}的联系记录", params.dict())
    return output_json(data={"fund_id": fundId}, message="")


@fund_app.get("/funds", summary="获取客户基金数据", response_model=FetchFundsResp)
async def fetch_fund_api(
        customerId: int = Query(..., title="客户ID", description="客户ID"),
        pageNo: int = Query(1, ge=0, title="页码", description="页码"),
        pageSize: int = Query(20, ge=0, title="页大小", description="页大小"),
        operator_id: int = Depends(check_operator)
):
    total, funds = FundServices().fetch_date(customerId, pageNo, pageSize)
    return output_json(data=funds, total=total, message="")


@fund_app.post(path="/funds/import", summary="批量导入基金数据接口", tags=["NEW!"])
async def import_fund_api(
        operator_id: int = Depends(check_operator),
        fund_file: UploadFile = File(..., title="基金数据", description="基金数据")
):
    customer_content = await fund_file.read()
    filename = fund_file.filename
    filename_suffix = filename.split('.')[-1]
    if filename_suffix not in ["xlsx"]:  # openpyxl只支持xlsx后缀文件
        raise InternalException(status.HTTP_623_FILE_ERROR, message="文件格式不对")

    with open(os.path.join(settings.FILES_DIR, filename), "wb") as f:
        f.write(customer_content)

    # 打开Excel文件
    workbook = load_workbook(os.path.join(settings.FILES_DIR, filename))
    # 选择第一个工作表
    sheet = workbook.active
    # 创建一个空列表，用于存储行数据
    rows_data = []
    # 迭代每一行并将其添加到列表中
    for index, row in enumerate(sheet.iter_rows()):
        row_data = [index]
        for cell in row:
            row_data.append(cell.value)
        rows_data.append(row_data)

    failure_data = []

    count = 0
    for data in rows_data[1:]:
        fund_data = {
            "salesman": data[3],
            "name": data[4],
            "fund_code": data[5],
            "company_name": data[6],
            "business_name": data[7],
            "delegate_state": data[8],
            "buy_date": data[9][0:4] + "-" + data[9][4:6] + "-" + data[9][6:],
            "amount": data[10],
            "fund_type": data[11]
        }
        customer = CustomerServices.check_exist_by_capital_account(data[1])
        if not customer:
            fund_data["index"] = data[0]
            fund_data["failure_reason"] = "客户账户不存在，说明该客户不存在"
            failure_data.append(fund_data)
            continue

        try:
            fund_data.update({"customer_id": customer["id"]})
            id = FundServices().create(**fund_data)
            LogServices().create(operator_id, f'新增了ID为{id}，客户ID为{customer["id"]}的客户基金数据', fund_data)
            if id:
                count += 1
        except Exception as e:
            logger.error(str(e))
            fund_data["index"] = data[0]
            fund_data["failure_reason"] = str(e)
            failure_data.append(fund_data)

    message = f'成功导入{count}条数据，失败{len(failure_data)}条数据'
    if failure_data:
        message += f'，其中失败的数据编号为{",".join([str(item["index"]) for item in failure_data])}'

    return output_json(data=None, message=message, failure_data=failure_data)
